package cn.sptpc.filter;

import cn.sptpc.entity.java.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class CheckLogin implements Filter {

    private String passUrl = "";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        passUrl = filterConfig.getInitParameter("passUrl");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setDateHeader("expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("pragma", "no-cache");
        response.setCharacterEncoding("UTF8");

        String arry[] =passUrl.split(";");
        boolean b = canIgnore(request, arry);
        if (b){
            filterChain.doFilter(request,response);
            return;
        }
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user != null){
        }else {
            response.sendRedirect("login.html");
        }
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
    private boolean canIgnore(HttpServletRequest request,String arry[]){
        for (String pass:arry){
            String str = request.getRequestURI();
            if (request.getRequestURI().indexOf(pass) >0){
                return true;
            }
        }
        return false;
    }
}
